import { http } from "@/utils/http";
import { baseUrlApi, handleApiResponse, handleApiError } from "./utils";
import type { ResultTable } from "./result/result_table";

// 将 apiPostRequest 和 apiGetRequest 提取出来作为独立函数
export const apiPostRequest = (
  basePath: string,
  endpoint: string,
  data = {}
) => {
  return http

    .request<ResultTable>("post", baseUrlApi(basePath + endpoint), {
      data
    })
    .then(handleApiResponse)
    .catch(handleApiError);
};

export const apiGetRequest = (
  basePath: string,
  endpoint: string,
  params = {}
) => {
  return http.request<ResultTable>("get", baseUrlApi(basePath + endpoint), {
    params
  });
};

export const apiFormUploadRequest = (
  basePath: string,
  endpoint: string,
  formData: FormData
) => {
  return http.request<ResultTable>("post", baseUrlApi(basePath + endpoint), {
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data"
    }
  });
};

export const createApiMethods = basePath => {
  return {
    all: params => apiGetRequest(basePath, "/all", params),
    list: params => apiGetRequest(basePath, "/list", params),
    create: data => apiPostRequest(basePath, "/create", data),
    update: data => apiPostRequest(basePath, "/update", data),
    remove: data => apiPostRequest(basePath, "/delete", data),
    importData: formData => apiFormUploadRequest(basePath, "/import", formData)
  };
};
